package cn.yunhe.shiro;

import cn.yunhe.model.Power;
import cn.yunhe.service.impl.UserServiceImpl;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

// AuthorizationFilter抽象类实现了javax.servlet.Filter接口，它是个过滤器。
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {

    @Resource
    private UserServiceImpl userService;

    @Override
    protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {
        //存放的是当前登录用户的 角色
        Subject subject = getSubject(req, resp);
        String principal = String.valueOf(subject.getPrincipals());
        System.out.println(principal);
        //rolesArray存放的是配置文件中的  角色的集合
//        String[] rolesArray = (String[]) mappedValue;

        HttpServletRequest request = (HttpServletRequest) req;
        String url = request.getRequestURI();
        System.out.println(url);
        //从数据库获取权限的角色集合
        Power power = userService.qetPowerByUrl(url);
        String role = power.getRole();
        String[] rolesArray =  role.split(",");

        System.out.println(rolesArray);

        if (rolesArray == null || rolesArray.length == 0) { //没有角色限制，有权限访问  
            return true;
        }
        for (int i = 0; i < rolesArray.length; i++) {
            if (subject.hasRole(rolesArray[i])) { //若当前用户是rolesArray中的任何一个，则有权限访问  
                return true;
            }
        }
        return false;
    }

    public UserServiceImpl getUserService() {
        return userService;
    }

    public void setUserService(UserServiceImpl userService) {
        this.userService = userService;
    }
}